package com.frank.fresh_mall.service.impl;

import com.frank.fresh_mall.common.Constant;
import com.frank.fresh_mall.exception.FreshMallException;
import com.frank.fresh_mall.exception.FreshMallExceptionEnum;
import com.frank.fresh_mall.model.dao.ProductMapper;
import com.frank.fresh_mall.model.pojo.Product;
import com.frank.fresh_mall.model.request.AddProductReq;
import com.frank.fresh_mall.model.request.ProductListReq;
import com.frank.fresh_mall.model.vo.CategoryVO;
import com.frank.fresh_mall.query.ProductListQuery;
import com.frank.fresh_mall.service.CategoryService;
import com.frank.fresh_mall.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品服务实现类
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper productMapper;

    @Resource
    private CategoryService categoryService;

    @Override
    public void add(AddProductReq addProductReq) {
        Product product = new Product();
        BeanUtils.copyProperties(addProductReq, product);
        Product oldProduct = productMapper.selectByName(addProductReq.getName());
        if (oldProduct != null) {
            throw new FreshMallException(FreshMallExceptionEnum.NAME_EXISTED);
        }
        int count = productMapper.insertSelective(product);
        if (count == 0) {
            throw new FreshMallException(FreshMallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public void update(Product updateProduct) {
        Product oldProduct = productMapper.selectByName(updateProduct.getName());
        // 同名且不同ID，不能继续修改
        if (oldProduct != null && !oldProduct.getId().equals(updateProduct.getId())) {
            throw new FreshMallException(FreshMallExceptionEnum.NAME_EXISTED);
        }
        int count = productMapper.updateByPrimaryKeySelective(updateProduct);
        if (count == 0) {
            throw new FreshMallException(FreshMallExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public void delete(Integer id) {
        Product oldProduct = productMapper.selectByPrimaryKey(id);
        // 查不到记录，无法删除
        if (oldProduct == null) {
            throw new FreshMallException(FreshMallExceptionEnum.DELETE_FAILED);
        }
        int count = productMapper.deleteByPrimaryKey(id);
        if (count == 0) {
            throw new FreshMallException(FreshMallExceptionEnum.DELETE_FAILED);
        }
    }

    @Override
    public void batchUpdateSellStatus(Integer[] productIds,
                                      Integer sellStatus) {
        productMapper.batchUpdateSellStatus(productIds, sellStatus);
    }

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productMapper.selectListForAdmin();
        PageInfo<Product> pageInfo = new PageInfo<>(products);
        return pageInfo;
    }

    @Override
    public Product detail(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo list(ProductListReq productListReq) {
        // 构建Query对象
        ProductListQuery productListQuery = new ProductListQuery();
        // 搜索处理
        if (!StringUtils.isEmpty(productListReq.getKeyword())) {
            String keyword = new StringBuilder().append("%")
                    .append(productListReq.getKeyword())
                    .append("%").toString();
            productListQuery.setKeyword(keyword);
        }
        // 目录处理：如果查某个目录下的商品，不仅是查出该目录下的，
        // 还把所有子目录的所有商品都查出来，所以要拿到一个目录id的list
        if (productListReq.getCategoryId() != null) {
            List<CategoryVO> categoryVOList = categoryService
                    .listCategoryForCustomer(productListReq.getCategoryId());
            List<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListReq.getCategoryId());
            getCategoryIds(categoryVOList, categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }
        // 排序处理
        String orderBy = productListReq.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
            PageHelper.startPage(productListReq.getPageNum(),
                    productListReq.getPageSize(),
                    orderBy);
        } else {
            PageHelper.startPage(productListReq.getPageNum(),
                    productListReq.getPageSize());
        }
        List<Product> productList = productMapper.selectList(productListQuery);
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        return pageInfo;
    }

    private void getCategoryIds(List<CategoryVO> categoryVOList,
                                List<Integer> categoryIds) {
        for (CategoryVO categoryVO : categoryVOList) {
            if (categoryVO.getChildCategory() != null) {
                categoryIds.add(categoryVO.getId());
                getCategoryIds(categoryVO.getChildCategory(), categoryIds);
            }
        }
    }
}